/**
 * 延迟执行函数
 * @param {number} ms 延迟时间(毫秒)
 * @returns {Promise}
 */
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

/**
 * 带重试机制的异步函数执行器
 * @param {Function} fn 要执行的异步函数
 * @param {Object} options 配置选项
 * @param {number} options.maxAttempts 最大重试次数
 * @param {number} options.initialDelay 初始延迟时间(毫秒)
 * @param {number} options.maxDelay 最大延迟时间(毫秒)
 * @param {Function} options.shouldRetry 判断是否应该重试的函数
 * @returns {Promise}
 */
export async function withRetry(fn, {
  maxAttempts = 5,
  initialDelay = 1000,
  maxDelay = 10000
} = {}) {
  let attempts = 0;
  let lastError;
  let currentDelay = initialDelay;

  while (attempts < maxAttempts) {
    try {
      return await fn();
    } catch (error) {
      lastError = error;
      console.log(`尝试 ${attempts + 1} 次失败: ${error.message}`);
      attempts++;
      if (attempts === maxAttempts) {
        throw new Error(`操作失败，已重试${maxAttempts}次: ${error.message}`);
      }

      // 使用指数退避策略
      await delay(currentDelay);
      currentDelay = Math.min(currentDelay * 2, maxDelay);
    }
  }

  throw lastError;
}